//
//  LCHtmlController.m
//  wan77
//
//  Created by jiukuyinyue on 2017/8/25.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LCVideoHtmlDetailsController.h"
#import "WXApi.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import <ShareSDKExtension/ShareSDK+Extension.h>
#import "NSString+Substring.h"

@interface LCVideoHtmlDetailsController () 

@property (nonatomic, assign) CGFloat delayTime;
@property (nonatomic, assign) CGFloat contentHeight;
@property (nonatomic,weak) UIButton *backButton;

@end

@implementation LCVideoHtmlDetailsController

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    if (self.value == 1) {
        [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"about:blank"]]];
        _LCPlayer.comeFrome = 0;
    }
    if (self.PlayAudio == 1) {
        [_LCPlayer play];//继续播放
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    // 移除掉
    //    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"share"];
}

- (void)dealloc
{
    _progressView.hidden = YES;
    [_progressView removeFromSuperview];
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];

    NSLog(@"调转链接 %@",_link);
    [self setupWebView];
    [self setupProgressView];
}
-(void)rightBtnAction {
    //1、创建分享参数
    NSArray* imageArray = @[[UIImage imageNamed:@"我的_设置_关于"]];//@[message.body[3]];
    //        （注意：图片必须要在Xcode左边目录里面，名称必须要传正确，如果要分享网络图片，可以这样传iamge参数 images:@[@"http://mob.com/Assets/images/logo.png?v=20150320"]）

    if (imageArray) {
        NSString *link = self.webView.URL.absoluteString;
        if (link.length < 5) {
            if (self.link.length > 5) {
                link = self.link;
            }else{
                link = @"http://fuyin.app.inping.com/user/download";
            }
        }
        NSURL *url = [NSURL URLWithString:link];
        NSString *title = self.webView.title;
        if (title.length == 0) {
            title = @"九酷福音";
        }
//        if ([ShareSDK isClientInstalled:SSDKPlatformTypeWechat] == NO) {
//            return;
//        }
        NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
        [shareParams SSDKSetupShareParamsByText:@"九酷福音"
                                         images:imageArray
                                            url:url
                                          title:title
                                           type:SSDKContentTypeAuto];
        //            //2、分享（可以弹出我们的分享菜单和编辑界面）
        [ShareSDK showShareActionSheet:nil items:@[
                                                   @(SSDKPlatformSubTypeWechatSession),
                                                   @(SSDKPlatformSubTypeWechatTimeline)
                                                   ]
                           shareParams:shareParams onShareStateChanged:^(SSDKResponseState state, SSDKPlatformType platformType, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error, BOOL end) {
            
            switch (state) {
                case SSDKResponseStateSuccess:
                {
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"分享成功"
                                                                                   message:nil
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                                          handler:^(UIAlertAction * action) {}];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                    break;
                }
                case SSDKResponseStateFail:
                {
                    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"分享失败"
                                                                                   message:[NSString stringWithFormat:@"%@",error]
                                                                            preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                                                          handler:^(UIAlertAction * action) {}];
                    
                    [alert addAction:defaultAction];
                    [self presentViewController:alert animated:YES completion:nil];
                    break;
                }
                default:
                    break;
            }
            
        }];
    }
}

-(void)setupWebView{
    self.view.backgroundColor = [UIColor whiteColor];
    // 根据生成的WKUserScript对象，初始化WKWebViewConfiguration
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
//    config.allowsInlineMediaPlayback = true;
    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, NAVIGATION_BAR_HEIGHT, self.view.bounds.size.width, self.view.bounds.size.height-NAVIGATION_BAR_HEIGHT) configuration:config];
    
    _webView.allowsBackForwardNavigationGestures = YES;//是否允许左右划手势导航,默认不允许
 
    // KVO 监听属性，具体参考 WKWebView 的头文件
    NSKeyValueObservingOptions observingOptions = NSKeyValueObservingOptionNew;
    [self.webView addObserver:self forKeyPath:@"title" options:observingOptions context:nil];
    
    [self.view addSubview:_webView];
    _webView.scrollView.bounces = NO;//禁止WebView滚动和回弹方法
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",_link]];//创建URL
    NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0f];//创建NSURLRequest
    [_webView loadRequest:request];//加载
    _webView.alpha = 0;
    
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else{
        // iOS7.0的特性 : 当滚动视图及其子类(UIScrollView/UIWebView/UITablewView/UICollectionView/UITexeView...)在自动布局时,遇到导航,里面的内容会自动的向下偏移64像素.
        self.automaticallyAdjustsScrollViewInsets = NO;
    }

}

-(BOOL)webView:(WKWebView *)webView shouldPreviewElement:(WKPreviewElementInfo *)elementInfo
{
    //获取请求的绝对路径.
    NSString *requestString = elementInfo.linkURL.absoluteString;
    //提交请求时候分割参数的分隔符
    NSArray *components = [requestString componentsSeparatedByString:@"#"];
    NSLog(@"%@",requestString);
    
    if ([components count] > 1)
    {
        self.value = 1;
        if (_LCPlayer.kstatus == LCMusicPlayerStatusPlaying ){
            
            //            [_PlaylistMgr removeAllPlaylists];
            [_LCPlayer pause];//暂停播放
            self.PlayAudio = 1;
            _LCPlayer.comeFrome = 1;
        }
        
    }
    return YES;
}




- (void)setupProgressView
{
    _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, self.navigationController.navigationBar.frame.size.height, ScreenWidth, 2)];
    [self.navigationController.navigationBar addSubview:_progressView];
    _progressView.progressTintColor = [UIColor redColor];
    _progressView.trackTintColor = [UIColor clearColor];
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {

        [self.progressView setProgress:self.webView.estimatedProgress animated:YES];
        
        if (self.webView.estimatedProgress < 1.0) {
            self.delayTime = 1 - self.webView.estimatedProgress;
            return;
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(self.delayTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.progressView.progress = 0;
            _webView.alpha = 1;//显示HTML界面
            _backButton.alpha = 0;
        });

    } else if ([keyPath isEqualToString:@"title"]) {
        if ([self.type isEqualToString:@"2"]) {
            self.title = @"主内商城";
        }else if([self.title isEqualToString:@"主内商城"]){
        }else{
            self.title = self.webView.title;
        }
        
    }
}


- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message{
//    NSLog(@"JS 调用了 %@ 方法，传回参数 %@",message.name,message.body);
    @try {
        if([message.name isEqualToString:@"share"])//此处name为JS传出信息打包的标志<name>
        {
            NSString *image= message.body[3];
            image = [image stringByReplacingOccurrencesOfString:@"./" withString:@"/"];
            image = [NSString stringWithFormat:@"%@%@",@"http://fuyin.app.inping.com/movie/",image];
            NSArray* imageArray = @[image];
            NSLog(@"imageArray = %@", imageArray);
            NSLog(@"message.body = %@", message.body);
            
            [self shareShengJingMessageWithImageArray:imageArray url:message.body[4] title:message.body[1] contentMessage:message.body[2] type:[message.body[0] integerValue]];
        }
    } @catch (NSException *exception) {
    }
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    webView.hidden = YES;
}
/**
 *  在发送请求之前，决定是否跳转
 *
 *  @param webView          实现该代理的webview
 *  @param navigationAction 当前navigation
 *  @param decisionHandler  是否调转block
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    if ([(navigationAction.request.URL.absoluteString)hasPrefix:@"http://fuyin.app.inping.com/"]){
        NSLog(@"11111");
    }
    
    NSString *url = [navigationAction.request.URL.absoluteString stringByRemovingPercentEncoding];
    NSLog(@"url = %@", url);
      //提交请求时候分割参数的分隔符
    NSArray *components = [url componentsSeparatedByString:@"#"];
 
    if ([components count] > 1)
    {
        self.value = 1;
        if (_LCPlayer.kstatus == LCMusicPlayerStatusPlaying ){
            
            //            [_PlaylistMgr removeAllPlaylists];
            [_LCPlayer pause];//暂停播放
            self.PlayAudio = 1;
            _LCPlayer.comeFrome = 1;
        }
        
    }
    
    if ([url containsString:@"alipay://"]) {//支付宝
        // url = alipay://alipayclient/?{"dataString":"h5_route_token=\"b623dcdee2328a907b74556a684cc4a7\"&is_h5_route=\"true\"","requestType":"SafePay","fromAppUrlScheme":"alipays"}
        NSString* dataStr=[url substringFromIndex:23];
        NSLog(@"%@",dataStr);
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[dataStr dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];
        NSMutableString* mString=[[NSMutableString alloc] init];
        [mString appendString:@"alipays://platformapi/startApp?appId=20000125&orderSuffix="];
        //url进行编码
        [mString appendString:[self encodeString:dict[@"dataString"]]];
        
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:mString]];
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }else if ([url containsString:@"weixin://"]) {
        
        NSDictionary *requestHeaders = navigationAction.request.allHTTPHeaderFields;
        if (requestHeaders[@"Referer"]) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
            decisionHandler(WKNavigationActionPolicyCancel);//不允许跳转
            return;
        }else{
            NSMutableURLRequest *mutableRequest = [navigationAction.request mutableCopy];
            [mutableRequest setValue:@"http://buy.9ku.com/" forHTTPHeaderField:@"Referer"];
            [webView loadRequest:mutableRequest];
        }
        
        decisionHandler(WKNavigationActionPolicyCancel);//这个地方必须进行不跳转
        return;
    }
    
    NSArray *array = @[
                       @"http://buy.9ku.com/wap/buy/pay?type=1&no=",
                       @"https://mclient.alipay.com/home/exterfaceAssign.htm",
                       @"https://mapi.alipay.com/gateway.do"
                       ];
    //商城的支付宝支付
    for (NSInteger i = 0; i < array.count; i++) {
        if([url containsString:array[i]]) {
            url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];
            decisionHandler(WKNavigationActionPolicyCancel);//这个地方必须进行不跳转,否则支付订单会失效
            return;
        }
    }
    if ([url hasPrefix:@"https://pos.baidu.com/"] || [url hasPrefix:@"https://eclick.baidu.com/"]) {
        
    }else{
        _link = url;
    }

    // 允许跳转
    decisionHandler(WKNavigationActionPolicyAllow);
}
-(NSString*)encodeString:(NSString*)unencodedString{
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    return encodedString;
}

//加载完成时调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
        if ([_link hasPrefix:@"http://fuyin.app.inping.com/movie/"]){
            
            if (self.titleStr) {
                NSDictionary *json = @{@"title":self.titleStr,
                                       @"link":_link
                                       };
                NSLog(@"历史纪录self.selectedVideoData = %@<><>%@", _LCPlayer.selectedVideoData,json);
                [_LCPlayer.selectedVideoData addObject:json];
                [[NSUserDefaults standardUserDefaults] setObject:_LCPlayer.selectedVideoData.copy forKey:@"TENVIDEOS"];
                NSLog(@"_LCPlayer.selectedVideoData = %@", _LCPlayer.selectedVideoData);

            }else{
                NSDictionary *json = @{@"title":self.title,
                                       @"link":_link
                                       };
                NSLog(@"历史纪录_LCPlayer.selectedVideoData = %@<><>%@", _LCPlayer.selectedVideoData,json);
                [_LCPlayer.selectedVideoData addObject:json];
                [[NSUserDefaults standardUserDefaults] setObject:_LCPlayer.selectedVideoData.copy forKey:@"TENVIDEOS"];
                NSLog(@"_LCPlayer.selectedVideoData = %@", _LCPlayer.selectedVideoData);

            }
                
            

        }
}

-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}
@end
